package 面试题32_1_不分行从上到下打印二叉树;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author ：xu_xiaofeng.
 * @Date ：Created in 12:38 2021/2/18
 * @Description：
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class Solution {
    public int[] levelOrder(TreeNode root) {

        if (root == null) {
            return new int[0];
        }

        ArrayList<Integer> resultList = new ArrayList<>();

        Deque<TreeNode> queue = new LinkedList<>();

        // 将头节点入队
        queue.add(root);

        TreeNode curNode;
        while (!queue.isEmpty()) {
            curNode = queue.pop();//出队
//            System.out.print(curNode.val + " ");
            resultList.add(curNode.val);

            // 将孩子节点入队
            if (curNode.left != null) {
                queue.add(curNode.left);
            }
            if (curNode.right != null) {
                queue.add(curNode.right);
            }
        }

        int[] result = new int[resultList.size()];

        int index = 0;
        for (int val : resultList) {
            result[index] = val;

            index++;
        }

        return result;
    }
}
